package com.credithc.customers.base.service.impl;

import com.credithc.customers.base.mapper.SystemInfoMapper;
import com.credithc.customers.base.po.SystemInfoPo;
import com.credithc.customers.base.service.ICacheService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zhukai
 * @date 2019/2/1 9:01
 */
@Service
public class CacheServiceImpl implements ICacheService {

    @Autowired
    private SystemInfoMapper systemInfoMapper;

    private static Map<String, Map<String, String>> systemMap;

    @Override
    public void cacheSystemInfo() {
        systemMap = new HashMap<>();
        List<SystemInfoPo> systems = systemInfoMapper.selectAll();

        for (SystemInfoPo po : systems) {
            Map<String, String> map = new HashMap<>();
            map.clear();
            map.put("name", po.getSystemName());
            map.put("roleSource", po.getRoleSource());
            map.put("relationSource", po.getRelationSource());
            map.put("mailReceiver", po.getMailReceiver());
            map.put("serviceUrl", po.getServiceUrl());
            map.put("parentSign", po.getParentId());
            map.put("secretKey", po.getSecretKey());
            systemMap.put(po.getSystemSign(), map);
        }
    }

    @Override
    public void clearSystemInfo() {
        systemMap.clear();
    }

    @Override
    public String getSystemNameBySign(String sign) {
        if (systemMap == null) {
            cacheSystemInfo();
        }
        if (systemMap.containsKey(sign)) {
            Map<String, String> map = systemMap.get(sign);
            if (map.containsKey("name")) {
                return map.get("name");
            }

        }
        return null;
    }

    @Override
    public boolean checkSystemSign(String systemSign, String subSystemSign) {
        if (systemMap == null) {
            cacheSystemInfo();
        }
        if (systemMap.containsKey(subSystemSign)) {
            Map<String, String> map = systemMap.get(subSystemSign);
            if (systemSign.equals(map.get("parentSign"))) {
                return true;
            }

        }
        return false;
    }
}
